<template>
  <el-dialog
    :title=" addForm&&addForm.id? '编辑文章' : '添加文章'"
    v-model="dialogVisble"
    width="70%"
    class="dialogBox"
    :before-close="closeBox"
  >
    <div class="dialogBox">
      <el-form
        ref="formRef"
        style="max-width:800px"
        :model="addForm"
        :rules="roleRules"
        label-width="auto"
        class="demo-dynamic"
      >
      <!--切换头-->
      <div class="tab-head">
      <div class="th-item" v-for="(tab,index) in tabList" :key="index" :class="tabId == tab.id?'th-item-ac':''">
       <div class="th-i-name" @click="tabChoose(tab.id)" :class="tabId == tab.id?'th-i-name-ac':'th-i-name-nor'">{{ tab.name }}</div>
      </div>
      </div>
      <!--文章基本信息-->
      <div class="" v-show="tabId == 1">
      <el-form-item prop="cate_id" :label="'分组'">
          <el-select
            v-model="addForm.cate_id"
            placeholder="选择分组"
            clearable
            size="large"
            style="width: 240px; margin-right: 10px"
          >
            <el-option
              v-for="item in cateArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="title" label="标题">
          <el-input v-model="addForm.title" />
        </el-form-item>

        <el-form-item label="封面">
          <div class="up-img-box">
            <el-image
              style="width: 100px; height: 100px"
              :src="addForm.thumb"
              fit="cover"
              :preview-src-list="[addForm.thumb]"
            />
            <div class="up-btn-box" @click="uploadImage">
              <input
                v-show="false"
                type="file"
                ref="fileInput"
                accept="image/*"
                @change="handleFileUpload"
              />
              <el-icon class="thumb-uploader-icon"><Plus /></el-icon>
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="description" label="简述">
          <el-input v-model="addForm.description" type="textarea" />
        </el-form-item>

        <el-form-item prop="sort" label="排序">
          <el-input v-model="addForm.sort" />
          <el-text class="mx-1" type="info">数字越小排序越靠前</el-text>
        </el-form-item>

        <el-form-item label="状态" prop="state" v-if="addForm&&addForm.id">
          <el-switch v-model="addForm.state" active-text="启用" inactive-text="禁用" />
        </el-form-item>
    
    </div>
    <!--文章内容-->
    <div class="" v-show="tabId == 2">
      <el-form-item label="内容" prop="text">
          <!-- 编辑器 自定义工具栏-->
           <!-- <quill-editor theme="snow" ref="myQuillEditor" v-model:content="addForm.text" :options="myEditorInit" content-type="html"></quill-editor> -->
           <!-- 编辑器 工具栏铺满-->
           <quill-editor theme="snow" ref="myQuillEditor" v-model:content="addForm.text" toolbar="full" content-type="html"></quill-editor>
           <!-- 使用自定义图片上传 -->
          <!-- <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" /> -->
        </el-form-item>
  </div>

      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeBox">取 消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, reactive,getCurrentInstance, nextTick ,watch,toRaw} from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { QuillEditor } from '@vueup/vue-quill'; //quill 编辑器
import '@vueup/vue-quill/dist/vue-quill.snow.css';//编辑器模板样式


const currentInstance = getCurrentInstance(); //获取main.js中挂载的实例
const { $api } = currentInstance.appContext.config.globalProperties;

const pors = defineProps({
  showdialog: {
    type: Boolean,
    default: false,
  },
  list: {
    type: Object,
    default: {},
  },
  cateArr: {
    type: Array,
    default: [{ name: "请选择用户组", id: 0 }],
  },
});

//tabs 切换
const tabList = ref([{id:1,name:'文章信息'},{id:2,name:'文章内容'}]);
const tabId = ref(1); //选中值
const tabChoose = (id) =>{
  tabId.value = id;
};// 选中标签

const formRef = ref<FormInstance>(); //定义form
//表单提交元素
const addForm = computed(() => pors.list);


const fileInput = ref(null); //上传控件

//表单元素的规则
const roleRules = reactive({
  title: [
    {
      required: true,
      message: "请输入标题",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
  cate_id: [
    {
      required: true,
      message: "请选择分组",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
  text: [
    {
      required: true,
      message: "请填写内容",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
});

const emits = defineEmits(["useConfirm", "useClose"]); //定义一个或多个自定义按钮事件 传递到父组件

const dialogVisble = ref(false); // 定义控制弹窗显隐的变量

const myQuillEditor = ref();//编辑器
//编辑器内容回显
// watch(
//   () => pors.list.text,
//   (newVal) => {
//     // console.log(newVal,"新值");
//     nextTick(()=>{
//       toRaw(myQuillEditor.value).setHTML = newVal; //值变更时赋值
//     });
//   }
// );

//关闭模态框
const closeBox = () => {
  // if (!formRef.value) return;
  // formRef.value.resetFields();
  dialogVisble.value = false; //重置为空
  emits("useClose", dialogVisble.value);
  tabId.value = 1;
};

//确定/提交
const submitForm = (formData: FormInstance | undefined) => {
  if (!formData) return;
  //校验
  formData.validate((valid) => {
    if (valid) {
      // console.log();

      dialogVisble.value = false;
      // console.log(addForm.value,"提交的数据");
      emits("useConfirm", addForm.value);
      formData.resetFields(); //重置为空
      tabId.value = 1;
    } else {
      // console.log("error submit!");
      return false;
    }
  });
};

//图片上传
const uploadImage =  () => {
  fileInput.value.click();
};
//input 点击事件
const handleFileUpload =(event) => {
  // console.log(event,"55");
  // file.value = event.target.files[0]; // 上传的内容
  var sizeLenght = event.target.files[0].size; //文件大小
  var size = sizeLenght / (1024 * 1024);
  // state.fileSize = size.toFixed(2); //文件大小 四舍五入保留小数后两位
  // state.fileName = event.target.files[0].name; // 文件名称
  // state.isUpLoad = true;

  // var maxlenght = 1020*1020*5; //未登录则最大5M
  // if (state.isLogin) {
  //   maxlenght = 1020*1020*20; //登录则最大20M
  // }
  // //大于100M时返回
  // if (sizeLenght > maxlenght) {
  //   // console.log("文件太大",state.fileSize/(1024*1024));
  //   msg({ type: "warn", text: "文件太大" });
  //   state.isUpLoad = false;
  //   return false;
  // }
   upFileService(event); //上传到服务器
//   console.log(event.target.files[0]);
};

//提交到服务器
const upFileService = (event) => {
  const formdata = new FormData();
  formdata.append("file",event.target.files[0]); //转为文件流
  formdata.append("name", event.target.files[0].name); //文件名称参数
  formdata.append("folder","article_img")
    $api.file_post("v1/login/upload/images", formdata).then((res) => {
      if(res.code == 200){
        addForm.value.thumb = res.data;
      }
  });

};

// 编辑器
const myEditorInit = ref({
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],//加粗 斜体 下划线 删除线
        ['blockquote','code-block'],//引用
        [{ 'size': ['small', false, 'large', 'huge'] }], //字体大小
        // [{ 'size': ['12px','13px','14px','15px','18px','36px']}], //字体大小
        [{ 'font': [] }],//字体
        [{ 'align': [] }],//对齐方式
        [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表 有序 无序
        [{ 'indent': '-1' }, { 'indent': '+1' }], //缩进
        [{'script':'sub'},{'script':'super'}],//上标 下标
        [{ 'header': 1 }, { 'header': 2 }], //标题
        ['link','image','video'], //连接 图片 视频
        [{ 'direction': 'rtl' }], //文本方向
        [{ 'color': [] }, { 'background': [] }], //字体颜色 背景颜色
        ['clean'] //清除文本格式
      ],//工具栏
    },
    placeholder: '请输入内容...'
});


// 将变量暴露出来
defineExpose({
  dialogVisble
});
</script>
<style>
.dialogBox{
  min-height:600px;
  max-height: 800px;
}
.up-img-box {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.up-btn-box {
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border: 1px solid #ddd;
  margin-left: 30px;
}
.ql-editor{
  max-height: 350px !important;
}
.ql-container{
  width: 100%;
}
.demo-tabs-editor{
  min-height: 600px;
}
.demo-tabs-editor .el-tabs__content{
  min-height: 520px;
}
.tab-head{
  width: 100%;
  display:flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #f1f1f1;
}
.th-item{
  padding: 10px;
}
.th-item-ac{border-bottom: 1px solid #409eff;}
.th-i-name{cursor: pointer;font-size:15px}
.th-i-name-nor{color: #999}
.th-i-name-ac{color: #409eff;font-weight: bold;}
</style>
